package com.liuwei.msmall.ware.listener;

import com.liuwei.msmall.common.dto.mq.OrderTo;
import com.liuwei.msmall.common.dto.mq.StockLockTo;
import com.liuwei.msmall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;

/**
 * @Classname StockReleaseListener
 * @Description TODO
 * @Date 2020/7/22 20:32
 * @Created by 刘
 */
@Slf4j
@RabbitListener(queues = {"stock.release.stock.queue"})
@Service
public class StockReleaseListener {

    @Autowired
    WareSkuService wareSkuService;

    /**
     * 库存自动解锁
     *  监听库存解锁消息队列
     *  1.下单成功，库存锁定失败，不用解锁
     *  2.下单失败，库存锁定成功，自动解锁
     *  3.下单成功，库存锁定成功，不用解锁
     * @param stockLockTo
     */
    @RabbitHandler
    public void handleStockRelease(StockLockTo stockLockTo, Message message, Channel channel) throws IOException {
        System.out.println("6分钟后触发自动解锁库存："+stockLockTo.toString()+"时间："+ LocalDateTime.now());
        try {
            wareSkuService.unlockStock(stockLockTo);
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("处理自动解锁库存消息异常：{}",e.getMessage());
            //有异常就将消息退回去重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }

    /**
     * 处理订单服务主动解锁逻辑
     * @param orderTo
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitHandler
    public void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("接收到订单关闭主动推送的消息："+orderTo.toString()+"时间："+ LocalDateTime.now());
        try {
            wareSkuService.unlockStock(orderTo);
            //手动确认消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            log.error("处理订单关闭主动推送的消息异常：{}",e);
            //有异常就将消息退回去重新入队
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }

    }
}
